/*
 * author james
 * date 2013-03-29
 * desc main js code for this project.for example validator for form...
 *
 */
var s_validator = {
    is_valid_nickname : function(lstr_nickname) {
	if (typeof lstr_nickname !== 'string')
	    return false;
	var lreg_nickname = /^[a-zA-Z0-9\u4e00-\u9fa5_]{4,32}$/;
	if (lreg_nickname.test(lstr_nickname))
	    return true;
	else
	    return false;
    },
    is_valid_email : function(lstr_email) {
	if (typeof lstr_email !== 'string')
	    return false;
	if (lstr_email.length > 255)
	    return false;
	var lreg_email = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
	if (lreg_email.test(lstr_email))
	    return true;
	else
	    return false;
    },
    is_valid_phone : function(lstr_phone) {
	if (typeof lstr_phone !== 'string')
	    return false;
	var lreg_phone = /^1[0-9]{10}$/;
	if (lreg_phone.test(lstr_phone))
	    return true;
	else
	    return false;
    },
    is_valid_tel : function(lstr_tel) {
	if (typeof lstr_tel !== 'string')
	    return false;
	var lreg_tel = /^((\d{3}-)?\d{8}|(\d{4}-)?\d{7}|(\d{4}-)?\d{8})$/;
	if (lreg_tel.test(lstr_tel))
	    return true;
	return false;
    },
    is_valid_password : function(lstr_password) {
	if (typeof lstr_password !== 'string')
	    return false;
	var lreg_password = /^[a-zA-Z0-9\u4e00-\u9fa5_]{6,16}$/;
	if (lreg_password.test(lstr_password))
	    return true;
	return false;
    },
    is_valid_industry3 : function(lstr_industry3) {
	return this.is_valid_sql_string(lstr_industry3, 10);
    },
    is_valid_company : function(lstr_company) {
	return this.is_valid_sql_string(lstr_company, 32);
    },
    is_valid_contactor : function(lstr_contactor) {
	return this.is_valid_sql_string(lstr_contactor, 16);
    },
    // is_valid_sql_string 判断其他的
    is_valid_sql_string : function(lstr_string, li_len) {
	if (typeof lstr_string !== 'string')
	    return false;
	if (lstr_string.length > li_len || lstr_string.length <= 0)
	    return false;
	var lreg_string = /(\'|(\%27)|\;|(\%3b)|\=|(\%3d)|\(|(\%28)|\)|(\%29)|(\/\*)|(\%2f\%2a)|(\*\/)|(\%2a\%2f)|\+|(\%2b)|\<|(\%3c)|\>|(\%3e)|(\-\-)|\[|\%5b|\]|\%5d)/;
	if (lreg_string.test(lstr_string))
	    return false;
	return true
    },
    is_valid_register_number : function(lstr_register_number) {
	if (typeof lstr_register_number !== 'string')
	    return false;
	var lreg_register_number = /^[0-9]{15}$/;
	if (lreg_register_number.test(lstr_register_number))
	    return true;
	else
	    return false;
    },
    is_valid_int : function(str) {
	if (typeof str !== 'string')
	    return false;
	var reg = /^\d{1,9}$/;
	if (reg.test(str))
	    return true;
	else
	    return false;
    },
    is_valid_url : function(url) {
	if (typeof url !== 'string')
	    return false;
	if (url.length > 255)
	    return false;
	var reg = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/i;
	if (reg.test(url))
	    return true;
	else
	    return false;
    },
    is_valid_sqlid : function(id) {
	return this.is_valid_int(id);
    },
    is_valid_id : function(id) {
	if (typeof id !== 'string')
	    return false;
	var reg = /^[a-zA-Z_]\w{0,31}$/;
	if (reg.test(id))
	    return true;
	else
	    return false;
    }
}

function pagination(opts) {
    var options = {
	'url' : '',
	'page_count' : 0,
	'page_size' : 10,
	'show_callback' : null,
	'pi' : 1,
	'selector' : ''
    };
    options.url = opts.url + '';
    options.page_count = opts.page_count - 0;
    options.page_size = opts.page_size - 0;
    options.selector = opts.selector;
    options.show_callback = opts.show_callback;

    this.show_info = function() {
	if (options.selector.length <= 0)
	    return;
	var pi = options.pi;
	if (0 === options.page_count)
	    pi = 0;
	$(options.selector)
		.text('当前第' + pi + '页/总共' + options.page_count + '页');
    }

    this.first_page = function() {
	options.pi = 1;
	options.show_callback(options);
    }

    this.prev_page = function() {
	if (options.pi > 1) {
	    --options.pi;
	    options.show_callback(options);
	}

    }

    this.next_page = function() {
	if (options.pi < options.page_count) {
	    ++options.pi;
	    options.show_callback(options);
	}

    }

    this.last_page = function() {
	options.pi = options.page_count;
	if (options.pi <= 0) {
	    options.pi = 1;
	}
	options.show_callback(options);
    }

    this.go_page = function(page) {
	page -= 0;
	if (page < 1 || page > options.page_count)
	    return;
	options.pi = page;
	options.show_callback(options);
    }

    this.cur_page = function() {
	options.show_callback(options);
    }

    this.get_page_index = function() {
	return options.pi;
    }

    this.get_page_count = function() {
	return options.page_count
    }

    this.set_page_count = function(count) {
	count -= 0;
	if (isNaN(count))
	    return;
	if (count < 0)
	    return;
	options.page_count = count;
	options.pi = 0;
	this.first_page();
    }

    this.inc_page_count = function() {
	options.page_count++;
    }

    this.dec_page_count = function() {
	var i = options.page_count;
	if (--i < 1)
	    i = 1;
	options.page_count = i;
    }

    this.set_page_count_without_action = function(count) {
	count -= 0;
	if (isNaN(count))
	    return;
	if (count < 0)
	    return;
	options.page_count = count;
    }
    options.show_callback(options);
}

function sub_string(str, len, suffix) {
    if (str == "" || str == null)
	return str;
    var new_len = 0;
    var new_str = '';
    var ch_reg = /[^\x00-\xff]/g;
    var sc = '';
    var slen = str.replace(ch_reg, '**').length;
    for (var i = 0; i < slen; i++) {
	sc = str.charAt(i).toString();
	if (sc.match(ch_reg) != null) {
	    new_len += 2;
	} else {
	    new_len++;
	}
	if (new_len > len) {
	    break;
	}
	new_str += sc;
    }

    if (suffix && slen > len) {
	new_str += suffix;
    }

    return new_str;
}

function mixed_length(str) {
    var i = 0, sum = 0;
    var len = str.length;
    for (; i < len; i++) {
	if ((str.charCodeAt(i) >= 0) && (str.charCodeAt(i) <= 255))
	    sum = sum + 1;
	else
	    sum = sum + 2;
    }
    return sum;
}

// 打开窗口，可以防止被过滤掉
function open_window(url, method, params, prefix) {
    var id = '_hx_open_window_123098567_', form = null;

    if (null == prefix)
	prefix = '';
    id += prefix;
    form = document.getElementById(id);
    if (null !== form)
	form.parentNode.removeChild(form);

    form = document.createElement('form');
    form.setAttribute('id', id);
    form.setAttribute('action', url);
    form.setAttribute('method', method);
    form.setAttribute('target', '_blank');
    var ele = null;
    for ( var i in params) {
	ele = document.createElement('input');
	ele.setAttribute('type', 'hidden');
	ele.setAttribute('name', i);
	ele.setAttribute('value', params[i]);
	form.appendChild(ele);
    }
    document.body.appendChild(form);

    form.submit();
}

/**
 * This tiny script just helps us demonstrate what the various example callbacks
 * are doing
 */
window.message_box = (function($) {
    "use strict";

    var elem, hideHandler, that = {};
    var alertStyles = [ 'alert-info', 'alert-warning', 'alert-success',
	    'alert-danger' ];

    that.init = function(options) {
	if (elem) {
	    return;
	}
	var html = '<div id="message_box_info" class="alert alert-info alert-block" style="display:none;width:500px;position:fixed;'
		+ 'left:50%;margin-left:-250px;top:30px;z-index:10000;"><button type="button" class="close">&times;</button>'
		+ '<span></span></div>';
	$("body").append(html);
	elem = $("#message_box_info");
	elem.find('button.close').click(function() {
	    that.hide();
	});
    };

    that.show = function(text, type, time) {
	if (elem == null || elem == undefined) {
	    that.init();
	}
	var alertClass = '';
	if (type == 'info') {
	    alertClass = 'alert-info';
	} else if (type == 'success') {
	    alertClass = 'alert-success';
	} else if (type == 'danger') {
	    alertClass = 'alert-danger';
	} else {
	    alertClass = 'alert-warning';
	}
	for (var i = 0; i < alertStyles.length; i++) {
	    elem.removeClass(alertStyles[i]);
	}
	if (alertClass != '') {
	    elem.addClass(alertClass);
	}

	clearTimeout(hideHandler);
	elem.find("span").html(text);
	elem.fadeIn();
	if (time != null || isNaN(time)) {
	    time = 4000;
	}

	hideHandler = setTimeout(function() {
	    that.hide();
	}, time);
    };

    that.hide = function() {
	elem.fadeOut();
    };

    return that;
}(jQuery));

/**
 * 对Date的扩展，将 Date 转化为指定格式的String *
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符 * 年(y)可以用 1-4
 * 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new Date()).pattern("yyyy-MM-dd
 * hh:mm:ss.S")==> 2006-07-02 08:09:04.423 (new Date()).pattern("yyyy-MM-dd E
 * HH:mm:ss") ==> 2009-03-10 二 20:09:04 (new Date()).pattern("yyyy-MM-dd EE
 * hh:mm:ss") ==> 2009-03-10 周二 08:09:04 (new Date()).pattern("yyyy-MM-dd EEE
 * hh:mm:ss") ==> 2009-03-10 星期二 08:09:04 (new Date()).pattern("yyyy-M-d
 * h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
Date.prototype.pattern = function(fmt) {
    var o = {
	"M+" : this.getMonth() + 1, // 月份
	"d+" : this.getDate(), // 日
	"h+" : this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, // 小时
	"H+" : this.getHours(), // 小时
	"m+" : this.getMinutes(), // 分
	"s+" : this.getSeconds(), // 秒
	"q+" : Math.floor((this.getMonth() + 3) / 3), // 季度
	"S" : this.getMilliseconds()
    // 毫秒
    };
    var week = {
	"0" : "/u65e5",
	"1" : "/u4e00",
	"2" : "/u4e8c",
	"3" : "/u4e09",
	"4" : "/u56db",
	"5" : "/u4e94",
	"6" : "/u516d"
    };
    if (/(y+)/.test(fmt)) {
	fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "")
		.substr(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
	fmt = fmt
		.replace(
			RegExp.$1,
			((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f"
				: "/u5468")
				: "")
				+ week[this.getDay() + ""]);
    }
    for ( var k in o) {
	if (new RegExp("(" + k + ")").test(fmt)) {
	    fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k])
		    : (("00" + o[k]).substr(("" + o[k]).length)));
	}
    }
    return fmt;
}

/**
 * 将时间格式字符川转化为时间对象
 */
function getDate(strDate) {
    var date = eval('new Date('
	    + strDate.replace(/\d+(?=-[^-]+$)/, function(a) {
		return parseInt(a, 10) - 1;
	    }).match(/\d+/g) + ')');
    return date;
}
/**
 * strDate,时间格式字符串 mft 格式定义 对Date的扩展，将 Date 转化为指定格式的String *
 * 月(M)、日(d)、12小时(h)、24小时(H)、分(m)、秒(s)、周(E)、季度(q) 可以用 1-2 个占位符 * 年(y)可以用 1-4
 * 个占位符，毫秒(S)只能用 1 个占位符(是 1-3 位的数字) * eg: * (new Date()).pattern("yyyy-MM-dd
 * hh:mm:ss.S")==> 2006-07-02 08:09:04.423 (new Date()).pattern("yyyy-MM-dd E
 * HH:mm:ss") ==> 2009-03-10 二 20:09:04 (new Date()).pattern("yyyy-MM-dd EE
 * hh:mm:ss") ==> 2009-03-10 周二 08:09:04 (new Date()).pattern("yyyy-MM-dd EEE
 * hh:mm:ss") ==> 2009-03-10 星期二 08:09:04 (new Date()).pattern("yyyy-M-d
 * h:m:s.S") ==> 2006-7-2 8:9:4.18
 */
function FormatDate(strDate, fmt) {
    var dt = getDate(strDate);
    return dt.pattern(fmt);
}
/**
 * JS获取url参数
 */
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null)
	return unescape(r[2]);
    return null;
}

function timeString() {
    var time = new Date();
    var string = '';
    string += time.getFullYear() + '-';
    var month = time.getMonth() + 1;
    if (month < 10) {
	string += '0' + month + '-';
    } else {
	string += month + '-';
    }
    if (time.getDate() < 10) {

	string += '0' + time.getDate() + ' ';
    } else {
	string += time.getDate() + ' ';
    }

    if (time.getHours() < 10) {
	string += '0' + time.getHours() + ':';
    } else {
	string += time.getHours() + ':';
    }

    if (time.getMinutes() < 10) {
	string += '0' + time.getMinutes() + ':';
    } else {
	string += time.getMinutes() + ':';
    }

    if (time.getSeconds() < 10) {
	string += '0' + time.getSeconds();
    } else {
	string += time.getSeconds();
    }
    return string;
}
/**
 * @see 自动缩放图片
 * @param id
 *                所在容器的ID
 * @param cname
 *                样式名称
 */
function ScaleImage(id, cname) {
    var rootEle = $("div[id='" + id + "']");
    var img = new Image();
    debugger;
    rootEle.find("img[src^='http://admin.bsapo.com']").each(function() {
	$(this).removeClass(cname);
	$(this).addClass(cname);
    });
    rootEle.find("img[src^='/ueditor/']").each(function() {
	$(this).removeClass(cname);
	$(this).addClass(cname);
    });
}

jQuery
	.extend({

	    createUploadIframe : function(id, uri) {
		// create frame
		var frameId = 'jUploadFrame' + id;
		var iframeHtml = '<iframe id="'
			+ frameId
			+ '" name="'
			+ frameId
			+ '" style="position:absolute; top:-9999px; left:-9999px"';
		if (window.ActiveXObject) {
		    if (typeof uri == 'boolean') {
			iframeHtml += ' src="' + 'javascript:false' + '"';

		    } else if (typeof uri == 'string') {
			iframeHtml += ' src="' + uri + '"';

		    }
		}
		iframeHtml += ' />';
		jQuery(iframeHtml).appendTo(document.body);

		return jQuery('#' + frameId).get(0);
	    },
	    createUploadForm : function(id, fileElementId, data) {
		// create form
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = jQuery('<form  action="" method="POST" name="'
			+ formId + '" id="' + formId
			+ '" enctype="multipart/form-data"></form>');
		if (data) {
		    for ( var i in data) {
			jQuery(
				'<input type="hidden" name="' + i + '" value="'
					+ data[i] + '" />').appendTo(form);
		    }
		}
		var oldElement = jQuery('#' + fileElementId);
		var newElement = jQuery(oldElement).clone();
		jQuery(oldElement).attr('id', fileId);
		jQuery(oldElement).before(newElement);
		jQuery(oldElement).appendTo(form);

		// set attributes
		jQuery(form).css('position', 'absolute');
		jQuery(form).css('top', '-1200px');
		jQuery(form).css('left', '-1200px');
		jQuery(form).appendTo('body');
		return form;
	    },

	    ajaxFileUpload : function(s) {
		// TODO introduce global settings, allowing the client to modify
		// them for all requests, not only timeout
		s = jQuery.extend({}, jQuery.ajaxSettings, s);
		var id = new Date().getTime()
		var form = jQuery.createUploadForm(id, s.fileElementId,
			(typeof (s.data) == 'undefined' ? false : s.data));
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;
		// Watch for a new set of requests
		if (s.global && !jQuery.active++) {
		    jQuery.event.trigger("ajaxStart");
		}
		var requestDone = false;
		// Create the request object
		var xml = {}
		if (s.global)
		    jQuery.event.trigger("ajaxSend", [ xml, s ]);
		// Wait for a response to come back
		var uploadCallback = function(isTimeout) {
		    var io = document.getElementById(frameId);
		    try {
			if (io.contentWindow) {
			    xml.responseText = io.contentWindow.document.body ? io.contentWindow.document.body.innerHTML
				    : null;
			    xml.responseXML = io.contentWindow.document.XMLDocument ? io.contentWindow.document.XMLDocument
				    : io.contentWindow.document;

			} else if (io.contentDocument) {
			    xml.responseText = io.contentDocument.document.body ? io.contentDocument.document.body.innerHTML
				    : null;
			    xml.responseXML = io.contentDocument.document.XMLDocument ? io.contentDocument.document.XMLDocument
				    : io.contentDocument.document;
			}
		    } catch (e) {
			jQuery.handleError(s, xml, null, e);
		    }
		    if (xml || isTimeout == "timeout") {
			requestDone = true;
			var status;
			try {
			    status = isTimeout != "timeout" ? "success"
				    : "error";
			    // Make sure that the request was successful or
			    // notmodified
			    if (status != "error") {
				// process the data (runs the xml through
				// httpData regardless of callback)
				var data = jQuery.uploadHttpData(xml,
					s.dataType);
				// If a local callback was specified, fire it
				// and pass it the data
				if (s.success)
				    s.success(data, status);

				// Fire the global callback
				if (s.global)
				    jQuery.event.trigger("ajaxSuccess", [ xml,
					    s ]);
			    } else
				jQuery.handleError(s, xml, status);
			} catch (e) {
			    status = "error";
			    jQuery.handleError(s, xml, status, e);
			}

			// The request was completed
			if (s.global)
			    jQuery.event.trigger("ajaxComplete", [ xml, s ]);

			// Handle the global AJAX counter
			if (s.global && !--jQuery.active)
			    jQuery.event.trigger("ajaxStop");

			// Process result
			if (s.complete)
			    s.complete(xml, status);

			jQuery(io).unbind()

			setTimeout(function() {
			    try {
				jQuery(io).remove();
				jQuery(form).remove();

			    } catch (e) {
				jQuery.handleError(s, xml, null, e);
			    }

			}, 100)

			xml = null

		    }
		}
		// Timeout checker
		if (s.timeout > 0) {
		    setTimeout(function() {
			// Check to see if the request is still happening
			if (!requestDone)
			    uploadCallback("timeout");
		    }, s.timeout);
		}
		try {

		    var form = jQuery('#' + formId);
		    jQuery(form).attr('action', s.url);
		    jQuery(form).attr('method', 'POST');
		    jQuery(form).attr('target', frameId);
		    if (form.encoding) {
			jQuery(form).attr('encoding', 'multipart/form-data');
		    } else {
			jQuery(form).attr('enctype', 'multipart/form-data');
		    }
		    jQuery(form).submit();

		} catch (e) {
		    jQuery.handleError(s, xml, null, e);
		}

		jQuery('#' + frameId).load(uploadCallback);
		return {
		    abort : function() {
		    }
		};

	    },
	    // jQuery.handleError is not a function
	    // 原因是，经测试handlerError只在jquery-1.4.2之前的版本中存在，jquery-1.6
	    // 和1.7中都没有这个函数了
	    handleError : function(s, xhr, status, e) {
		// If a local callback was specified, fire it
		if (s.error) {
		    s.error.call(s.context || s, xhr, status, e);
		}

		// Fire the global callback
		if (s.global) {
		    (s.context ? jQuery(s.context) : jQuery.event).trigger(
			    "ajaxError", [ xhr, s, e ]);
		}
	    },

	    uploadHttpData : function(r, type) {
		var data = !type;
		data = type == "xml" || data ? r.responseXML : r.responseText;
		// If the type is "script", eval it in global context
		if (type == "script")
		    jQuery.globalEval(data);
		// Get the JavaScript object, if JSON is used.
		if (type == "json")
		    data = eval("(" + data + ")");
		// evaluate scripts within html
		if (type == "html")
		    jQuery("<div>").html(data).evalScripts();

		return data;
	    }
	})
